layui.use(['layer', 'upload', 'element', 'viewer'], function () {

    var layer = parent.layer === undefined ? layui.layer : top.layer,
        $ = layui.jquery,
        element = layui.element,
        upload = layui.upload;

    var Viewer = layui.viewer;


    //var upload_config = APP.CONFIG.upload;
    var upload_config = {
        storage: 'local'
    };
    var uploadInstObj = {};

    var initUploader = function () {
        var url = $('.upload_url').val();

        $('[id^=upload-file]').each(function (i) {
            var _this = $(this);
            var sortId = _this.attr('id');
            var index = sortId.substr(11);

            //var upload_element = 'upload-file' + i; // 上传按钮的上级元素
            var upload_element = 'upload-file' + index; // 上传按钮的上级元素
            var upload_btn = 'upload-btn' + index; // 上传按钮

            var upload_btn_elm = _this.find('#' + upload_btn); // 上传按钮元素
            var field = upload_btn_elm.attr('data-field');
            var folder = upload_btn_elm.attr('data-folder');
            var place = upload_btn_elm.attr('data-place');
            var max_file_size = upload_btn_elm.attr('data-max_file_size');
            var extensions = upload_btn_elm.attr('data-extensions');
            var multi = upload_btn_elm.attr('data-multi');

            if (max_file_size == '' || max_file_size == undefined) {
                max_file_size = '500';
            }
            if (multi == 'false') {
                multi = false;
            } else {
                multi = true;
            }
            if (extensions == '' || extensions == undefined) {
                extensions = 'jpg|jpeg|gif|png';
            }
            if (extensions == 'mp4') {
                max_file_size = 1024*3;
            }

            if (field == '' || field == undefined) {
                field = 'file';
            }
            if (folder == '' || folder == undefined) {
                folder = 'default';
            }
            if (place == '' || place == undefined) {
                place = upload_config.storage;
            }

            uploaderReadyForFile(url, '#' + upload_element, '#' + upload_btn, max_file_size, extensions, multi, field, folder, place);
        });
    };

    var uploaderReadyForFile = function (url, upload_element, upload_btn, max_file_size, extensions, multi, field, folder, place) {
        var ori_src = $('.load_img').attr('src');

        var _upload_btn_elm = $(upload_element).find(upload_btn);
        var total_count = _upload_btn_elm.attr('data-total_count');
        if (!total_count) {
            total_count = 1;
        }
        var count = _upload_btn_elm.attr('data-count');
        if (!count) {
            count = 0;
        }

        var uploadInst = upload.render({
            //elem: upload_element,
            elem: upload_btn,
            url: url,
            data: {
                //'field': field,
                'folder': folder,
                'place': place,
                'multi': multi,
                'total_count': total_count,
                'count': count
            },
            field: 'file', // 设定文件域的字段名，默认为file
            //field: field,
            accept: 'file', // 允许上传时校验的文件类型 file（所有文件）
            //acceptMime: 'image/*', // 只显示图片文件
            exts: extensions, // 允许上传的文件后缀
            //multiple: multi, // 是否允许多文件上传
            multiple: false, // 禁止多文件上传
            size: max_file_size, // 限制文件大小，单位 KB
            //auto: false, // 选择文件后不自动上传
            //bindAction: '#uploaderAction', // 指向一个按钮触发上传
            choose: function (obj) {
                // 将每次选择的文件追加到文件队列
                var files = obj.pushFile();

                // 预读本地文件，如果是多文件，则会遍历
                obj.preview(function (index, file, result) {
                    // console.log(index); // 得到文件索引
                    // console.log(file); // 得到文件对象
                    // console.log(result); // 得到文件base64编码，比如图片

                    //obj.resetFile(index, file, '123.jpg'); // 重命名文件名，layui 2.3.0 开始新增

                    //这里还可以做一些 append 文件列表 DOM 的操作

                    //obj.upload(index, file); // 对上传失败的单个文件重新上传，一般在某个事件中使用
                    delete files[index]; // 删除列表中对应的文件，一般在某个事件中使用
                });
            },
            before: function (obj) {
                layer.load(); // 上传loading
                console.log(obj);
                console.log(total_count, count);
                if (multi) {
                    // 多文件
                    if (total_count - count < 1) {
                        //layer.msg('最多上传' + total_count + '张');
                        console.log('最多上传' + total_count + '张');
                        // 无效
                        return false;
                    }
                } else {
                    // 预读本地文件示例，不支持ie8
                    obj.preview(function (index, file, result) {
                        //console.log(result);
                        $(upload_element).find('.load_img').attr('src', result); // 图片链接（base64）
                    });
                }
            },
            progress: function (n) {
                $(upload_element).find('.upload-progress').css('display', 'block');
                var percent = n + '%'; // 获取进度百分比
                //console.log(percent);
                element.progress('upload_progress', percent); // 可配合 layui 进度条元素使用
            },
            allDone: function (obj) { // 当文件全部被提交后，才触发
                console.log(obj.total); // 得到总文件数
                console.log(obj.successful); // 请求成功的文件数
                console.log(obj.aborted); // 请求失败的文件数
            },
            done: function (res) {
                layer.closeAll('loading'); // 关闭loading
                $(upload_element).find('.upload-progress').css('display', 'none');

                // var total_count = $(upload_btn).attr('data-total_count');
                // var count = $(upload_btn).attr('data-count');
                // console.log(count);
                // if (count >= total_count) {
                //     layer.msg('最多上传' + total_count + '张');
                //     return;
                // }

                layer.msg(res.msg);
                if (res.code == 1) {
                    var _upload_btn_elm = $(upload_element).find(upload_btn);
                    var count = _upload_btn_elm.attr('data-count');
                    if (!count) {
                        count = 0;
                    }

                    /*if (!multi) {
                        var existFile = $(upload_element).find('.exist-file');
                        if (existFile.length > 0) {
                            $(upload_element).find('.multi-file').remove();
                        }
                    }*/

                    $(upload_element).find('.' + field).val(res.filepath);

                    if (multi) {
                        if (field == 'files') {
                            var $class = field + '_' + (count);
                            var $item = '';
                            $item += '<div class="layui-input-block multi-file">';
                            $item += '<div class="layui-inline" style="width: 80%;">';
                            $item += '<input type="text" class="layui-input ' + $class + '" name="' + field + '[]" value="' + res.filepath + '" disabled>';
                            $item += '</div>';
                            $item += '<div class="layui-inline">';
                            $item += '<button type="button" class="layui-btn layui-btn-danger"><i class="layui-icon layui-icon-close-fill del"></i></button>';
                            $item += '</div>';

                            $(upload_element).parent().after($item);
                        } else {
                            var $class = field + '_' + (count);
                            var $item = '';
                            $item += '<span class="multi-file">';
                            $item += '<input type="hidden" class="' + $class + '" name="' + field + '[]" value="' + res.filepath + '">';
                            if (extensions == 'mp4') {
                                // 视频
                                $item += '<a class="viewer-video" href="javascript:;"><video class="exist-file" src="' + res.full_filepath + '"></video></a>';
                            } else {
                                // 图片
                                $item += '<a href="javascript:;"><img class="exist-file" src="' + res.full_filepath + '" layer-src="' + res.full_filepath + '" alt="" /></a>';
                            }
                            $item += '<img class="del" src="' + APP.STATIC + 'admin/pages/image/del.png" alt="">';
                            $item += '</span>';

                            var _upload_btn_elm = $(upload_element).find(upload_btn);
                            _upload_btn_elm.before($item);
                        }

                        // 上传文件数加1
                        count++;
                        _upload_btn_elm.attr('data-count', count);

                        COMMON.viewImage(Viewer, document.getElementsByClassName('upload_file-box'));
                    }
                } else {
                    if (!multi) {
                        $(upload_element).find('.load_img').attr('src', ori_src);
                    }
                }

                // 重载上传实例，支持重载全部基础参数
                var _upload_btn_elm = $(upload_element).find(upload_btn);
                var total_count = _upload_btn_elm.attr('data-total_count');
                if (!total_count) {
                    total_count = 1;
                }
                var count = _upload_btn_elm.attr('data-count');
                if (!count) {
                    count = 0;
                }
                uploadInst.reload({
                    data: {
                        //'field': field,
                        'folder': folder,
                        'place': place,
                        'multi': multi,
                        'total_count': total_count,
                        'count': count
                    },
                });
            },
            error: function (index, upload) {
                layer.closeAll('loading'); // 关闭loading
                $(upload_element).find('.upload-progress').css('display', 'none');
            }
        });

        if (multi) {
            COMMON.viewImage(Viewer, document.getElementsByClassName('upload_file-box'));
        }

        uploadInstObj[upload_element.substr(1)] = uploadInst;
        console.log(uploadInstObj);
    };

    // 删除
    $(document).find('.upload_file-box').on('click', '.del', function () {
        var _this = $(this);
        var element = _this.parents('.multi-file'); // 要删除元素
        var parent_elm = _this.parents('.upload_file-box'); // 父元素
        var upload_element = parent_elm.attr('id');

        element.remove();
        layer.msg('删除成功');

        var _upload_btn_elm = parent_elm.find('.upload-btn');

        var field = _upload_btn_elm.attr('data-field');
        var total_count = _upload_btn_elm.attr('data-total_count');
        if (!total_count) {
            total_count = 1;
        }
        var count = _upload_btn_elm.attr('data-count');
        if (!count) {
            count = 0;
        }
        if (parent_elm.find('.multi-file').length <= 0) {
            parent_elm.find('.' + field).val('');
        }

        count--;
        _upload_btn_elm.attr('data-count', count);

        // 重载上传实例，支持重载全部基础参数
        var folder = _upload_btn_elm.attr('data-folder');
        var place = _upload_btn_elm.attr('data-place');
        var multi = _upload_btn_elm.attr('data-multi');
        if (folder == '' || folder == undefined) {
            folder = 'default';
        }
        if (multi == 'false') {
            multi = false;
        } else {
            multi = true;
        }
        if (place == '' || place == undefined) {
            place = upload_config.storage;
        }

        var uploadInst = uploadInstObj[upload_element];
        if (uploadInst) {
            uploadInst.reload({
                data: {
                    //'field': field,
                    'folder': folder,
                    'place': place,
                    'multi': multi,
                    'total_count': total_count,
                    'count': count
                },
            });
        }
    });

    // 重载上传实例
    function reloadUploader() {
        //
    }

    if ($('.upload_file-box').length > 0) {
        initUploader();
    }
});
